// pages/sfc_fb/sfc_rc.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //普通选择器：（普通数组）
    array: ['1人', '2人', '3人', '4人', '5人', '6人'],
    index: 0,//默认显示位置
    //时间选择器：
    time: '请输入乘车时间',
    //日期选择器：
    date: '请输入乘车日期',
    imgs: [],
    placeholder: '请选择',
    user:null,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var userInfo = wx.getStorageSync("userInfo");
    if (userInfo) {
      this.setData({
        user: userInfo
      })
    }else{
      wx.showToast({
        title: "请先登录",
        icon: 'none',
        duration: 2000
      })
      //返回上一页
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/user/user'
        })
      }, 2000)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /*返回上一页*/
  navigateBack: function () {
    var self = this;
    var pages = getCurrentPages();
    if (pages.length == 1) {
      if (self.data.circleId && self.data.circleId > 0) {
        wx.redirectTo({
          url: '../../circle/index/index?circleId=' + self.data.circleId
            + '&circleName=' + (self.data.circleName || '')
        });
      } else {
        wx.switchTab({
          url: "../../home/grouplist/grouplist"
        });
      }
    } else {
      wx.navigateBack({ changed: true });//返回上一页  
    }
  },

  formSub(e) {
    var that = this
    var data = e.detail.value
    var images = that.data.imgs
    var checked = that.data.checked
    var title = false;
    if (data.departure == '') {
      title = '出发地不能为空';
    } else if (data.destination == '') {
      title = '目的地不能为空';
    } else if (data.date == '' || data.date == '请输入乘车日期' || data.time == '' || data.time == '请输入乘车时间') {
      title = '请输入乘车日期';
    } else if (data.number == '' || data.number == '请选择乘客人数') {
      title = '请选择乘客人数';
    } else if (data.remarks == '') {
      title = '请输入备注说明';
    } else if (images.length == 0) {
      title = '请上传图片';
    } else if (data.name == '') {
      title = '请填写联系人姓名';
    } else if (data.tel == '' || !(/^1[34578]\d{9}$/.test(data.tel))) {
      title = '请检查手机号格式';
    } else if (that.data.checked == false) {
      title = '阅读并同意《平台协议条款》';
    } 
    if (title == false){
      data.images = images.join(',')
      data.type = '1'
      data.uid = that.data.user.id
      data.city = wx.getStorageSync("city")
      var fromData = data
      app.wxRequest('post', '/Samecity/Freeride/release', fromData, (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: "发布成功",
            icon: 'none',
            duration: 2000
          })
          //返回上一页
          setTimeout(function () {
            wx.navigateBack();
          }, 2000)
          
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }, (err) => {
        console.log(err)
      })
    }else{
      wx.showToast({
        title: title,
        icon: 'none',
        duration: 2000,
      })
    }
  },

  //时间选择器：
  bindTimeChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },
  //日期选择器：
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },


  // 上传图片
  chooseImg: function (e) {
    let that = this;
    var imgs = that.data.imgs;
    var imgsLength = imgs.length  
    wx.chooseImage({
      count: 9 - imgsLength,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var filePaths = res.tempFilePaths
        var filePathsLength = filePaths.length;
        var failNum = 0;
        for (var i = 0; i < filePathsLength; i++) {
            wx.uploadFile({
              url: app.globalData.theUrl1 + '/Samecity/Upload/uploadFile',
              filePath: filePaths[i],
              name: 'fileData',
              formData: {},
              success: (successBack) => {
                var imgs = that.data.imgs;
                var data=JSON.parse(successBack.data)
                if (data.code==0){
                  imgs.push(data.url);
                  that.setData({
                    imgs: imgs
                  })
                }else{
                  failNum++;
                }
              },
              fail: (failBack) => {
                failNum++;
              },
            });
        }
        wx.showToast({
          title: '总共' + filePathsLength + '张上传成功,' + failNum + '张上传失败！',
          icon: 'none'
        });
      }
    });
  },
  // 删除图片
  deleteImg: function (e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },
  // 预览图片
  previewImg: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  //普通选择器：
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
})